package influxdb

import (
	"encoding/json"
	"fmt"
	"github.com/cihub/seelog"
	"github.com/influxdata/influxdb/client/v2"
	"time"
)

const (
	FTPFILE = "ftpfile"
)

type FtpFile struct {
	Time     time.Time
	FileTag  string
	FileName string
	// -1 是不能删除，0是可以删除 1 为已删除
	Status int
}

func (c *Connect) SelectFtpFileByStauts(table string, status int) []*FtpFile {
	sql := fmt.Sprintf("SELECT * FROM %s where status = %d order by time tz('%s');",
		table, status, c.TimeZone)
	res, err := c.queryDB(sql)
	if err != nil {
		seelog.Error(err.Error())
	}
	return toFtpFile(res)
}

func (c *Connect) GroupInsertFtpFile(files []*FtpFile, tableName string) {
	len := len(files)
	cut := 10000
	if len > cut {
		p := len / cut
		for i := 0; i < p; i++ {
			c.insertFtpFtile(files[i*cut:cut*(i+1)], tableName)
		}
		if len%cut > 0 {
			c.insertFtpFtile(files[cut*p:len], tableName)
		}

	} else {
		c.insertFtpFtile(files, tableName)
	}
}

func (c *Connect) insertFtpFtile(files []*FtpFile, tableName string) int {

	var cPoint []*client.Point
	for _, value := range files {
		tags := map[string]string{
			"filetag": value.FileTag,
		}
		fields := map[string]interface{}{
			"filename": value.FileName,
			"status":   value.Status,
		}
		pt, err := client.NewPoint(tableName, tags, fields, value.Time)
		if err != nil {
			seelog.Error(err)
			return -1
		} else {
			cPoint = append(cPoint, pt)
		}
	}
	return c.insert(cPoint)
}

func toFtpFile(result []client.Result) []*FtpFile {
	var resFlow []*FtpFile
	var rarray []map[string]interface{}
	for _, res := range result {
		if res.Err == "" {
			for _, row := range res.Series {
				cloumns := row.Columns
				for _, values := range row.Values {
					rmap := make(map[string]interface{}, len(cloumns))
					for index, va := range values {
						rmap[cloumns[index]] = va
					}
					rarray = append(rarray, rmap)
				}
			}
		} else {
			seelog.Error(res.Err)
		}
		rjson, err := json.Marshal(rarray)
		if err != nil {
			seelog.Error(err)
		}
		json.Unmarshal(rjson, &resFlow)
	}
	return resFlow
}
